package com.google.code.p.restrpc.core.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dz
 */
public class NamedThreadFactory implements ThreadFactory {
    
    /**
     * @return
     */
    public static ThreadFactory newFactory() {
        return new NamedThreadFactory("restrpc-threadpool", false);
    }
    
    /**
     * @param prefix
     * @return
     */
    public static ThreadFactory newFactory(String prefix) {
        return new NamedThreadFactory(prefix, false);
    }
    
    /**
     * @param prefix
     * @param daemon
     * @return
     */
    public static ThreadFactory newFactory(String prefix, boolean daemon) {
        return new NamedThreadFactory(prefix, daemon);
    }
    
    private final AtomicInteger threadCounter = new AtomicInteger(0);
    
    private final String prefix;
    
    private final boolean daemon;
    
    private final ThreadGroup threadGroup;
    
    /**
     * @param prefix
     * @param daemon
     */
    public NamedThreadFactory(String prefix, boolean daemon) {
        this.prefix = prefix;
        this.daemon = daemon;
        SecurityManager s = System.getSecurityManager();
        threadGroup = (s == null) ? Thread.currentThread().getThreadGroup()
                                 : s.getThreadGroup();
    }
    
    public Thread newThread(Runnable runnable) {
        String name = prefix + "-thread-" + threadCounter.incrementAndGet();
        Thread result = new Thread(threadGroup, runnable, name, 0);
        result.setDaemon(daemon);
        return result;
    }
    
    public ThreadGroup getThreadGroup() {
        return threadGroup;
    }
}
